package com.qidian.mes.qc.service.impl;/**
 * ClassName:CheckCodeServiceImpl
 * Package:com.qidian.mes.qc.service.impl
 **/

import com.qidian.mes.pojo.EncodingRules;
import com.qidian.mes.qc.mapper.CheckCodeMapper;
import com.qidian.mes.qc.service.CheckCodeService;
import com.qidian.mes.qc.service.CheckItemService;
import com.qidian.mes.util.Tools;
import com.qidian.mes.util.exceptions.ServiceException;
import com.qidian.mes.util.pojo.QdResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @Author ppc
 * @Conpany study
 * @Description:
 * @Time 2024/4/10 11:14
 *
 **/
@Service
public class CheckCodeServiceImpl implements CheckCodeService {

    @Value("${codePatternLength}")
    private int codePatternLength;
    @Autowired
    private CheckCodeMapper checkCodeMapper;

    @Override
    public QdResult query(String rulesName) {
        String code = "";
        EncodingRules encodingRules = checkCodeMapper.selectByName(rulesName);
        String pattern = "";
        String dateStr = Tools.now();
        switch(encodingRules.getRulesPattern()){
            case 1:
                pattern = dateStr.split("-")[0];
                break;
            case 2:
                pattern = dateStr.substring(0,7).replace("-","");
                break;
            case 3:
                pattern = dateStr.replace("-","");
                break;

            default:
               throw new ServiceException("编号的格式类别错误，应该从1，2，3中选择，但是传递的是："+encodingRules.getRulesPattern());
        }
        /**
         * 比较生成的pattern和现在存储在数据表中的pattern是否相同
         */
        if(pattern.equals(encodingRules.getCurrPattern())){
            //给最大顺位号+1就可以生产编码了
            String max = encodingRules.getMaxNumber()+1+"";
            //给max前面补0
            while(max.length() < codePatternLength){
                max = "0"+max;
            }
            //生成
            code = encodingRules.getRulesPer() + pattern + max;
            encodingRules.setMaxNumber(encodingRules.getMaxNumber()+1);
        }else {
            //最大顺位号重置为1
            String max = "1";
            //补0
            while(max.length()<codePatternLength){
                max  = "0" +max;
            }
            code = encodingRules.getRulesPer() + pattern + max;
            //修改数据库中的最大编码和currPattern
            encodingRules.setMaxNumber(1);
            encodingRules.setCurrPattern(pattern);
        }
        checkCodeMapper.updateById(encodingRules);
        return QdResult.success("OK",code);

    }
}
